﻿using System.Security.Claims;
using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.User;
using Provenance.Read.Api.Application.Command.User;
using Provenance.Read.Api.Dto.User;

namespace Provenance.Read.Api.Application.CommandHandler.User
{
    public class GetApiPermissionListCommandHandler : IRequestHandler<GetApiPermissionListCommand, ApiResult<IList<GetApiPermissionListResponseDTO>>>
    {
        private readonly IApiPermissionRepository _apiPermissionRepository;
        private readonly IRoleApiPermissionRepository _roleApiPermissionRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ILogger<GetApiPermissionListCommandHandler> _logger;
        private readonly IMapper _mapper;
        public GetApiPermissionListCommandHandler(IApiPermissionRepository apiPermissionRepository, IRoleApiPermissionRepository roleApiPermissionRepository, IHttpContextAccessor httpContextAccessor, ILogger<GetApiPermissionListCommandHandler> logger, IMapper mapper, IUserRoleRepository userRoleRepository)
        {
            _apiPermissionRepository = apiPermissionRepository;
            _roleApiPermissionRepository = roleApiPermissionRepository;
            _httpContextAccessor = httpContextAccessor;
            _logger = logger;
            _mapper = mapper;
            _userRoleRepository = userRoleRepository;
        }
        public async Task<ApiResult<IList<GetApiPermissionListResponseDTO>>> Handle(GetApiPermissionListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var user = _httpContextAccessor.HttpContext.User;
                var UserId = user.FindFirst(type: ClaimTypes.NameIdentifier)?.Value;
                //获取当前用户ID对应的所有api权限
                var roleUser = await _userRoleRepository.GetAllAsync(x => x.UserId == int.Parse(UserId) && x.IsDeleted == false);
                var roleIds = roleUser.Select(x => x.RoleId).ToArray();
                var roleApiPermissions = await _roleApiPermissionRepository.GetAllAsync(x => roleIds.Contains(x.RoleId));
                var apiPermissionIds = roleApiPermissions.Select(x => x.ApiPermissionId).ToArray();
                var apiPermissionList = await _apiPermissionRepository.GetAllAsync(x => apiPermissionIds.Contains(x.ApiPermissionId));
                var result=_mapper.Map<IList<GetApiPermissionListResponseDTO>>(apiPermissionList);
                return ApiResult<IList<GetApiPermissionListResponseDTO>>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error in GetApiPermissionListCommandHandler: " + ex.Message);
                return ApiResult<IList<GetApiPermissionListResponseDTO>>.Failure(ex.Message);
            }
        }
    }
}
